<template>
  <div>
    <!-- 覆盖版即将到站 2018/3/7 11:44 zuoW -->
    <Row>
      <Form label-position="right" :label-width="90">
        <i-col :span="4">
          <FormItem label="装载种类">
            <Select v-model="tabParam.isContainer" filterable placeholder="请选择集装箱种类" style="width: 200px">
              <Option v-for="item in queryForm" :value="item.isContainer" :key="item.isContainer">{{ item.truckTypeName }}</Option>
            </Select>
          </FormItem>
        </i-col>
        <i-col :span="8" :offset="12">
          <Button :type="dispatchOrderType==='autoDispatchOrder'?'error':'primary'" @click="autoDispatchOrder">自动派单</Button>
          <Button :type="dispatchOrderType==='dispatchOrder'?'error':'primary'" @click="dispatchOrder">手动派单</Button>
        </i-col>
      </Form>
    </Row>
    <Row>
      <i-col span="24">
        <Tabs v-model="tabParam.status">
          <template v-for="item in orderStatues">
            <TabPane :label="item.label" :name="item.val"></TabPane>
          </template>
        </Tabs>

        <!--即将到站-->
        <!--<tablePage ref="inspectionTab" :filterMethod="tabFilterMethod" :api="queryMainOrderListByPage" :param="tabParam" sort-name="orderNo" sort-type="desc" :isStartLoad="true"-->
        <!--v-if="tabParam.status==orderStatues[1].val">-->
        <!--<template slot-scope="props">-->
        <!--<Table :columns="comingStationColumn" :data="props.data" @on-sort-change="props.sortChange" border @on-selection-change="mainOrderTabSelectChange"></Table>-->
        <!--</template>-->
        <!--</tablePage>-->

        <!--已到站-->
        <tablePage ref="inspectionTab" :filterMethod="tabFilterMethod" :api="queryMainOrderListByPage" :param="tabParam" sort-name="endStationTime desc,orderNo " sort-type="asc" :isStartLoad="true"
          v-if="tabParam.status==orderStatues[0].val">
          <template slot-scope="props">
            <Table :columns="inspectionColumnArrived" :data="props.data" @on-sort-change="props.sortChange" border @on-selection-change="mainOrderTabSelectChange"></Table>
          </template>
        </tablePage>
      </i-col>
    </Row>

    <!--<xlinkModal v-model="operatModal.sendNoticeShow" title="手动派单" width="500">-->
    <!--<dispatchOrder v-if="operatModal.sendNoticeShow" :currentMainOrder="mainOrderCurrentRow" @close="sendNoticeClose"></dispatchOrder>-->
    <!--</xlinkModal>-->

    <!--<xlinkModal v-model="operatModal.sendNoticeShow" title="自动派单" width="500">
      &lt;!&ndash;&ndash;&gt;
      <sendNoticeMainOrder v-if="operatModal.sendNoticeShow" :currentMainOrder="mainOrderCurrentRow" @close="sendNoticeClose"></sendNoticeMainOrder>
    </xlinkModal>-->

    <!--<xlinkModal v-model="operatModal.sendNoticeShow" title="发送通知" width="400">-->
    <!--&lt;!&ndash;&ndash;&gt;-->
    <!--<sendNoticeMainOrder v-if="operatModal.sendNoticeShow" :currentMainOrder="mainOrderCurrentRow" @close="sendNoticeClose"></sendNoticeMainOrder>-->
    <!--</xlinkModal>-->

    <xlinkModal v-model="operatModal.viewDetailShow" className="vertical-center-modal" title="查看详情" width="1000">
      <viewDetail v-if="operatModal.viewDetailShow" :currentMainOrder="mainOrderCurrentRow" @dispatchTofleetDataRefresh="thisDataRefresh"></viewDetail>
    </xlinkModal>

    <xlinkModal v-model="operatModal.autoDispatchOrderShow" className="vertical-center-modal" title="自动派单" width="1000">
      <autoDispatchOrder v-if="operatModal.autoDispatchOrderShow" @close="autoDispatchOrderClose"></autoDispatchOrder>
    </xlinkModal>

    <!-- 选择车队，要派单了（整列派单，派单逻辑交给父页面） -->
    <xlinkModal v-model="operatModal.dispatchModalShow" className="vertical-center-modal" title="整列派单" width="700">
      <dispatchToFleet v-if="operatModal.dispatchModalShow" @close="operatModal.dispatchModalShow = false" @assignment="assignmentToFleet"></dispatchToFleet>
    </xlinkModal>
    <!--<xlinkModal v-model="operatModal.assignmentOrderShow" title="整列派单" width="768">
      <assignmentOrder v-if="operatModal.assignmentOrderShow" :currentMainOrder="mainOrderCurrentRow" @close="sendAssignmentOrderClose"></assignmentOrder>
    </xlinkModal>-->
  </div>
</template>

<script>
  import tablePage from '@components/table/tablePage.vue'
  import {queryMainOrderListByPage, dispatchToFleetOrder2, dispatchRemoveV3} from '@api/backEnd/mainOrder/index'
  import xlinkModal from '@components/modal/xlinkModal'
  import sendNoticeMainOrder from '../mainOrder/components/sendNoticeMainOrder'
  import {assignmentOrder, getAutoDispatcher} from '@api/backEnd/station/index'
  import viewDetail from './components/viewDetail'
  import moment from 'moment'
  import _ from 'lodash'
  import {mapGetters} from 'vuex'
  import dispatchToFleet from './components/dispatchToFleet'
  import autoDispatchOrder from './components/autoDispatchOrder'

  export default {
    name: 'coming--tation-inspection',
    data () {
      let dispatchOrderType = 'dispatchOrder'
      let operatModal = {
        viewDetailShow: false,
        sendNoticeShow: false,
        assignmentOrderShow: false,
        dispatchDriverShow: false,
        viewDetailForFleetShow: false,
        dispatchModalShow: false,
        autoDispatchOrderShow: false
      }
      let mainOrderCurrentRow = {}
      /* 即将到站 */
      let comingStationColumn = [
        {
          type: 'index',
          width: 60
        },
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '联运单号',
          key: 'orderNo',
          width: 200
        },
        {
          title: '车次',
          key: 'endTrainNumber',
          width: 100
        },
        // {
        //   title: '所在股道',
        //   key: 'emptyTrack',
        //   width: 100
        // render: (h, params) => {
        //   return (<span>{params.row.paraPositionTrack}</span>)
        // }
        // },
        {
          title: '到达时间',
          width: 250,
          render: (h, params) => {
            let thisdata = params.row.endStationTime
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '终点站',
          key: 'endStationName',
          width: 250
        }
      ]
      // 已到站
      let inspectionColumnArrived = [
        {
          type: 'index',
          width: 60
        },
        {
          type: 'selection',
          width: 60,
          align: 'center'
        },
        {
          title: '联运单号',
          key: 'orderNo',
          width: 200
        },
        {
          title: '车次',
          key: 'endTrainNumber',
          width: 100
        },
        // {
        //   title: '所在股道',
        //   width: 100,
        //   render: (h, params) => {
        //     return (<span>{params.row.paraPositionTrack}</span>)
        //   }
        // },
        {
          title: '到达时间',
          width: 250,
          render: (h, params) => {
            let thisdata = params.row.endStationTime
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        },
        {
          title: '终点站',
          key: 'endStationName',
          width: 250
        }
      ]
      let operatBtn = {
        title: '操作',
        key: 'action',
        align: 'center',
        minWidth: 250,
        render: (h, params) => {
          // let sendNoticeBtn = (<i-button type="error" size="small" style="margin-right: 5px;" onClick={() => this.sendNoticeAction(params.row)}>预通知车队</i-button>)
          let viewDetailBtn = (<i-button type="primary" size="small" style="margin-right: 5px;" onClick={() => this.viewDetailAction(params.row)}>查看详情</i-button>)
          let dispatchRemove = ''
          if (params.row.assignmentTime) {
            dispatchRemove = (<i-button type="warning" size="small" style="margin-right: 5px;" onClick={() => this.dispatchRemove(params.row)}>撤销派单</i-button>)
          }
          let btnArray = []
          // powerUtil.contains('sendNotice') && btnArray.push(sendNoticeBtn)
          powerUtil.contains('viewDetail') && btnArray.push(viewDetailBtn)
          btnArray.push(dispatchRemove)
          if (+params.row.dispatchcontaninerscount > 0) {
            let infoBtn = (<i-button type="warning" size="small" style="margin-right: 5px;">已分组派单</i-button>)
            btnArray.push(infoBtn)
          }
          return (btnArray)
        }
      }
      if (powerUtil.contains('comingFleet')) {
        // 车队端增加字段【派单时间】
        comingStationColumn.push({
          title: '派单时间',
          width: 200,
          render: (h, params) => {
            let thisdata = params.row.assignmentTime
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        })
        inspectionColumnArrived.push({
          title: '派单时间',
          width: 200,
          render: (h, params) => {
            let thisdata = params.row.assignmentTime
            thisdata = thisdata ? moment(thisdata).format('YYYY-MM-DD HH:mm') : ''
            return (<span>{thisdata}</span>)
          }
        })
      }
      comingStationColumn.push(operatBtn)
      inspectionColumnArrived.push(operatBtn)
      let orderStatues = [
        // { label: '即将到站', val: '1,2,3,4' },
        {label: '已到站', val: '5'}
      ]
      let queryForm = [
        {'isContainer': '', 'truckTypeName': '全部'},
        {'isContainer': 1, 'truckTypeName': '集装箱'},
        {'isContainer': 0, 'truckTypeName': '整车运输'}
      ]
      let tabParam = {startStationCode: '', endStationCode: '', status: orderStatues[0].val}
      let checkedMainOrder = []
      let datas = {dispatchOrderType, checkedMainOrder, orderStatues, comingStationColumn, inspectionColumnArrived, tabParam, queryForm, operatModal, mainOrderCurrentRow, queryMainOrderListByPage}
      return datas
    },
    computed: {
      ...mapGetters(['currentUser', 'activeMenu'])
    },
    methods: {
      autoDispatchOrderClose () {
        this.stationGetAutoDispatcher()
        this.operatModal.autoDispatchOrderShow = false
      },
      // 判断当前是否有自动派单
      stationGetAutoDispatcher () {
        getAutoDispatcher().then(res => {
          if (+res.data.isSuccess === 1) {
            if (moment(res.data.data.beginTime).format('HH:mm:ss') <= moment().format('HH:mm:ss') && moment(res.data.data.endTime).format('HH:mm:ss') >= moment().format('HH:mm:ss')) {
              this.dispatchOrderType = 'autoDispatchOrder'
            } else {
              this.dispatchOrderType = 'dispatchOrder'
            }
          } else {
            this.dispatchOrderType = 'dispatchOrder'
          }
        })
      },
      /**
       * TODO(撤销派单)
       * @auther zhangQ
       * @date 2018/6/18 20:44
       */
      dispatchRemove (row) {
        dispatchRemoveV3({mainOrderNo: row.orderNo}).then(res => {
          if (+res.data.isSuccess === 1) {
            this.$Notice.success({
              title: '成功',
              desc: '撤销派单成功'
            })
            row._disabled = false
            row.assignmentTime = ''
          }
        })
      },
      tabFilterMethod (arr) {
        return arr
      },
      mainOrderTabSelectChange (rows) {
        this.checkedMainOrder = rows
      },
      /**
       * TODO(向车队派单)
       * @auther zhangQ
       * @date 2018/6/12 17:26
       */
      assignmentToFleet (assignmentForm, fleetList) {
        console.log('stationLogisticsMonitoring')
        console.log('assignmentToFleet (assignmentForm, fleetList)')
        console.log('assignmentToFleet', assignmentForm)
        let assignmentFormClone = _.cloneDeep(assignmentForm)
        if (!(assignmentFormClone.checkTrackName.length > 0)) {
          this.$Notice.warning({
            title: '错误',
            desc: '车队必选'
          })
          return
        }
        // assignmentFormClone.checkTrackName = assignmentFormClone.checkTrackName.join(',')
        let maps = []
        this.checkedMainOrder.forEach((item) => {
          assignmentFormClone.checkTrackName.forEach((fleetItem) => {
            let fleetName = _.find(fleetList, (fleetNameItem) => {
              return fleetNameItem.id === fleetItem
            })
            let obj = {
              dispatchOrgId: this.currentUser.userId,
              dispatchOrgName: this.currentUser.loginName,
              orgId: fleetName.id,
              orgName: fleetName.login_name,
              dispatchType: 1, // 整列派单
              mainOrderNo: item.orderNo,
              startStationCode: item.startStationCode,
              startStationName: item.startStationName,
              endStationCode: item.endStationCode,
              endStationName: item.endStationName,
              isContainer: item.isContainer,
              paraPositionTrack: assignmentFormClone.paraPositionTrack,
              estimateArriveTime: assignmentFormClone.estimateArriveTime,
              paraPositionTime: assignmentFormClone.estimateArriveTime
            }
            maps.push(obj)
          })
        })
        let xlFleetOrderList = maps
        let otherInfo = {
          outAddress: assignmentFormClone.address,
          userAddressId: assignmentFormClone.userAddressId,
          memo: assignmentFormClone.memo,
          outContacts: assignmentFormClone.contacts,
          outMobile: assignmentFormClone.contactsMobile,
          kilometreNum: assignmentFormClone.kilometreNumber
        }
        let param = {xlFleetOrderList, otherInfo}
        // 开始发送
        dispatchToFleetOrder2(param).then(res => {
          if (+res.data.isSuccess === 1) {
            this.$Notice.success({
              title: '成功',
              desc: '派单成功'
            })
            this.operatModal.dispatchModalShow = false
            this.checkedMainOrder = []
            this.$refs['inspectionTab'].dataRefresh()
          } else {
            this.$Notice.error({
              title: '警告',
              desc: '派单失败' + res.data.res
            })
          }
        })
      },
      dataRefresh () {
        this.$refs['inspectionTab'].dataRefresh()
      },
      sendNoticeAction (row) {
        this.mainOrderCurrentRow = row
        this.operatModal.sendNoticeShow = true
      },
      sendNoticeClose (operatStr) {
        this.operatModal.sendNoticeShow = false
        if (operatStr === 'sendNotice') {
          this.$refs['inspectionTab'].dataRefresh()
        }
      },
      sendAssignmentOrderClose (operatStr) {
        this.operatModal.assignmentOrderShow = false
        if (operatStr === 'sendAssignmentOrderClose') {
          this.$refs['inspectionTab'].dataRefresh()
        }
      },
      // assignmentOrderAction (row) {
      //   this.mainOrderCurrentRow = row
      //   let mainOrderNo = row.orderNo
      //   this.$Modal.confirm({
      //     title: '整列派单',
      //     content: '确定派单？',
      //     onOk: () => {
      //       let param = { mainOrderNo, paraPositionTime: '' }
      //       assignmentOrder(param).then(res => {
      //         console.log(res.data)
      //         if (res.data.isSuccess === 1) {
      //           this.$Message.info('派单成功')
      //           this.$refs['inspectionTab'].dataRefresh()
      //         } else {
      //           this.$Message.error(res.data.res)
      //         }
      //       })
      //     },
      //     onCancel: () => {
      //     }
      //   })
      // },
      /**
       * TODO(查看详情)
       * @auther zhangQ
       * @date 2018/3/27 11:01
       */
      viewDetailAction (row) {
        this.mainOrderCurrentRow = row
        this.operatModal.viewDetailShow = true
      },
      thisDataRefresh () {
        this.$refs['inspectionTab'].dataRefresh()
      },
      /**
       * TODO(手动派单)
       * @auther zhangQ
       * @date 2018/6/12 11:17
       */
      dispatchOrder () {
        let isDisPatch = ''
        this.checkedMainOrder.forEach(item => {
          if (item.dispatchcontaninerscount > 0) {
            isDisPatch += item.orderNo + '<br>'
          }
        })
        if (isDisPatch) {
          this.$Notice.warning({
            title: '操作提示',
            desc: '运单<br>' + isDisPatch + '已派单（或已分组派单）'
          })
          return
        }
        if (this.checkedMainOrder.length > 0) {
          this.operatModal.dispatchModalShow = true
        } else {
          this.$Notice.warning({
            title: '操作提示',
            desc: '请选择主运单'
          })
        }
      },
      /**
       * TODO(自动派单)
       * @auther zhangQ
       * @date 2018/6/12 11:17
       */
      autoDispatchOrder () {
        this.operatModal.autoDispatchOrderShow = true
      }
    },
    created () {
    },
    watch: {
      tabParam: {
        handler: function (val, oldVal) {
          setTimeout(() => {
            this.$refs['inspectionTab'].dataRefresh()
          }, 200)
          this.checkedMainOrder = []
        },
        deep: true
      },
      operatModal: {
        handler: function (val, oldVal) {
          if (!val.autoDispatchOrderShow) {
            this.autoDispatchOrderClose()
          }
        },
        deep: true
      }
    },
    mounted () {
      this.stationGetAutoDispatcher()
    },
    components: {tablePage, sendNoticeMainOrder, xlinkModal, assignmentOrder, viewDetail, dispatchToFleet, autoDispatchOrder}
  }
</script>

<style scoped>

</style>
